﻿using Inovout.Data.Service;
using KuaJing.Orders.Domain;
using System.Collections.Concurrent;
using System.Linq;

namespace KuaJing.Orders.Service
{
    public class ProductService : RepositoryService<Product>
    {
        private static readonly ConcurrentDictionary<string, Product> productDictionary = new ConcurrentDictionary<string, Product>();

        public Product GetProduct(string productName)
        {
            return productDictionary.GetOrAdd(productName, (key) =>
            {
                var product = base.StatelessQuery().SingleOrDefault(p => p.Name == key);
                if (product == null)
                {
                    product = new Product { Number = (productDictionary.Count + 1).ToString("0000"), Name = key, Category = GetProductCategory(key) };
                    base.Save(product);
                }
                return product;
            });
        }
        private ProductCategory GetProductCategory(string productName)
        {
            if (productName.Contains("退税"))
            {
                return ProductCategory.Drawback;
            }
            else if (productName.Contains("赊销"))
            {
                return ProductCategory.Financing;
            }
            return ProductCategory.Clearance;
        }
    }
}
